const moment = require('moment')
//导入题库的数据模型
const { T_user } = require('../models/t_user')
const { T_user_and_academy } = require('../models/T_user_and_academy')


// 获取用户所有信息的业务处理
exports.getAllT_user = async (req, res) => {
    try {
        const t_user = await T_user.findAll();
        res.json({
            "code": 200,
            "mag": "查询全部成功",
            "data": t_user
        })
    } catch (error) {
        res.json({
            "code": 500,
            "msg": "查询全部失败",
        })
    }
}

const { T_academy } = require('../models/T_academy')
const { T_user_and_subject } = require('../models/T_user_and_subject')
const { T_subjects } = require('../models/t_exam_subjects')
const { T_user_and_a_c_s } = require('../models/t_user_and_a_c_s')
//通过id来查询用户信息
exports.getT_userById = async (req, res) => {
    const { id } = req.params;
    console.log('ID is:', id);
    try {
        // 1. 查询用户信息
        const t_user = await T_user.findByPk(id);

        if (!t_user) {
            return res.json({
                'code': 203,
                'msg': '找不到用户信息'
            });
        }

        // 2. 查询属于该用户的所有科目关联数据
        const userAndACS = await T_user_and_a_c_s.findAll({
            where: {
                user_id: id
            }
        });

        if (!userAndACS || userAndACS.length === 0) {
            return res.json({
                'code': 203,
                'msg': '该用户没有相关科目数据'
            });
        }

        // 3. 提取科目关联数据中的科目 ID
        const subjectIds = userAndACS.map(item => item.subject_id);

        // 4. 查询这些科目的详细信息
        const subjects = await T_subjects.findAll({
            where: {
                id: subjectIds
            }
        });

        if (!subjects || subjects.length === 0) {
            return res.json({
                'code': 203,
                'msg': '找不到相关科目信息'
            });
        }

        // 5. 构建科目信息对象数组，去重复
        const uniqueSubjects = {};
        subjects.forEach(subject => {
            uniqueSubjects[subject.id] = subject;
        });

        const subjectArray = Object.values(uniqueSubjects).map(subject => ({
            id: subject.id,
            name: subject.subject
        }));

        // 6. 返回用户信息以及相关科目信息
        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": {
                'own': t_user,
                'sub': subjectArray
            }
        });
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message
        });
    }
};

//通过id来查询用户信息
exports.getT_userById = async (req, res) => {
    const { id } = req.params;
    console.log('ID is:', id);
    try {
        // 1. 查询用户信息
        const t_user = await T_user.findByPk(id);

        if (!t_user) {
            return res.json({
                'code': 203,
                'msg': '找不到用户信息'
            });
        }

        // 2. 查询属于该用户的所有科目关联数据
        const userAndACS = await T_user_and_a_c_s.findAll({
            where: {
                user_id: id
            }
        });

        if (!userAndACS || userAndACS.length === 0) {
            return res.json({
                'code': 203,
                'msg': '该用户没有相关科目数据'
            });
        }

        // 3. 提取科目关联数据中的科目 ID
        const subjectIds = userAndACS.map(item => item.subject_id);

        // 4. 查询这些科目的详细信息
        const subjects = await T_subjects.findAll({
            where: {
                id: subjectIds
            }
        });

        if (!subjects || subjects.length === 0) {
            return res.json({
                'code': 203,
                'msg': '找不到相关科目信息'
            });
        }

        // 5. 构建科目信息对象数组，去重复
        const uniqueSubjects = {};
        subjects.forEach(subject => {
            uniqueSubjects[subject.id] = subject;
        });

        const subjectArray = Object.values(uniqueSubjects).map(subject => ({
            id: subject.id,
            name: subject.subject
        }));

        // 6. 返回用户信息以及相关科目信息
        res.json({
            "code": 200,
            "msg": "查询成功",
            "data": {
                'own': t_user,
                'sub': subjectArray
            }
        });
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message
        });
    }
};

//更新用户信息
exports.updatet_user = async (req, res) => {
    const { id } = req.params//id
    const { user_name, password, real_name, role, status, image_path } = req.body;
    console.log(id);

    try {
        const [updateRows] = await T_user.update(
            { user_name, password, real_name, role, status, image_path },
            { where: { id } },
        );

        if (updateRows > 0) {
            const updateTime = new Date(); // 获取当前时间并转换为 ISO 格式

            const formattedDate = moment(updateTime).format('YYYY-MM-DD');
            res.json({
                "code": 200,
                "msg": "更新成功",
                "data": formattedDate
            });
        } else {
            res.json({
                "code": 404,
                "msg": `内容未更改`,
            });
        }

    }
    catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        })
    }
}

//添加用户
exports.createt_user = async (req, res) => {
    const { user_name, password, real_name, role, status, image_path } = req.body;
    try {
        const t_user = await T_user.create({
            user_name, password, real_name, role, status, image_path
        });
        const updateTime = new Date(); // 获取当前时间并转换为 ISO 格式
        res.json({
            "code": 200,
            "msg": '创建成功',
            "data": t_user,
        });
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};

//注销用户
exports.deleteT_userById = async (req, res) => {
    const { id } = req.params;
    try {
        const deletedRows = await T_user.destroy({
            where: { id },
        });
        if (deletedRows > 0) {
            res.json({
                "code": 200,
                "msg": '删除成功',
            });
        } else {
            res.json({
                "code": 404,
                "msg": `用户ID为${id}的记录不存在`,
            });
        }
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};

//修改密码、
exports.updatePassword = async (req, res) => {
    const { user_id, old_password, new_password } = req.body;

    try {
        const user = await T_user.findOne({
            where: {
                id: user_id
            }
        });

        if (!user) {
            res.status(404).json({

                msg: '用户不存在'
            });
            return;
        }

        const oldPassword = user.password;

        if (old_password != oldPassword) {
            res.json({
                'code': 203,
                'msg': '旧密码不正确'
            });
            return;
        }

        if (old_password === new_password) {
            res.status(400).json({ msg: '新旧密码不能一致' });
            return;
        }
        // 更新密码
        user.password = new_password;
        await user.save();

        res.json({
            code: 200,
            msg: '密码更新成功'
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: error.message
        });
    }
};

//找回密码
exports.retrievePassword = async (req, res) => {
    const { real_name, phone_num, new_password } = req.body;

    try {
        const user = await T_user.findOne({
            where: {
                real_name: real_name
            }
        });

        if (!user) {
            res.json({
                'code': 404,
                'msg': '用户不存在'
            });
            return;
        }

        const phone = user.phone_num
        if (phone != phone_num) {
            res.json({
                'code': 404,
                'msg': '该号码与用户不匹配'
            });
            return;
        }


        // 更新密码
        user.password = new_password;
        await user.save();

        res.json({
            code: 200,
            msg: '找到成功，请记住你的密码'
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: error.message
        });
    }
};